import { defineStore } from "pinia";
import { useState } from "@/hooks";
import { computed } from "vue";
import type { UserLoginResult } from "@/api";
import { userMobileLogin, reloadToken, getUserInfo } from "@/api";
import {
  mountGetTokenFunc,
  mountRefreshTokenFunc,
  mountLogoutFunc,
} from "@/config";

/**
 * 用户信息
 */
export type UserInfo = UserLoginResult;

/** 用户信息初始化 */
export const getUserInfoInit = () => {
  return {
    uid: 0,
    nickname: "",
    avatar: "",
    token: "",
    refresh_token: "",
  };
};

export const useUserStore = defineStore("user", () => {
  /** 用户钩子 */
  const userInfoHook = useState<UserInfo>(getUserInfoInit(), {
    moduleKey: "USER_INFO",
    debug: true,
    cache: true,
  });

  /**
   * 基本状态
   */
  const userInfo = computed(() => userInfoHook.state);

  /** token */
  const token = computed(() => userInfo.value.token);

  mountGetTokenFunc(() => token.value);

  /** refreshToken */
  const refreshToken = computed(() => userInfo.value.refresh_token);

  const refreshTokenFunc = async () => {
    const {
      data: { token },
    } = await reloadToken({
      Authorization: refreshToken.value,
    });
    userInfoHook.updateState({
      token,
    });
  };
  mountRefreshTokenFunc(refreshTokenFunc);

  /** 是否登录 */
  const isLogin = computed(() => !!token.value);

  /** 退出登录 */
  const noApiLogout = () => {
    userInfoHook.resetState();
  };

  const logout = async () => {
    noApiLogout();
    // 退出登录api
  };

  /** 登录 */
  const login = async () => {
    noApiLogout();
    const { data } = await userMobileLogin({
      mobile: "19812345678",
      code: "8888",
    });

    userInfoHook.updateState(data);

    return data;
  };

  mountLogoutFunc(noApiLogout);

  /** 获取用户信息 */
  const getInfo = async () => {
    const { data } = await getUserInfo();
    userInfoHook.updateState({
      ...data.user_info,
      refresh_token: refreshToken.value,
      token: token.value,
    });
    return data;
  };

  return {
    userInfo,
    isLogin,
    login,
    logout,
    getInfo,
  };
});
